package com.zhyonk.config.propreties;

import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zhyonk.domain.ToutiaoToken;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Objects;

@Data
@Component
@ConfigurationProperties(prefix = "toutiao")
public class ByteDanceProperties {

    private static String appId;


    private static String appSecret;

    private static String grantType = "client_credential";

    private static ToutiaoToken toutiaoToken;

    public static String getGrantType() {
        return grantType;
    }

    public static void setGrantType(String grantType) {
        ByteDanceProperties.grantType = grantType;
    }

    private static String token;

    public static String getAppId() {
        return appId;
    }

    public void setAppId(String appId) {
        ByteDanceProperties.appId = appId;
    }

    public static String getAppSecret() {
        return appSecret;
    }

    public void setAppSecret(String appSecret) {
        ByteDanceProperties.appSecret = appSecret;
    }

    public static String getToken() {
        if (Objects.isNull(token)){
            token = getTokenFromServer();
        }
        //检测过期
        if (toutiaoToken.getExpiresTime() < (System.currentTimeMillis() /1000) + 60){
            token = getTokenFromServer();
        }
        return token;
    }

    private static String getTokenFromServer() {
        HashMap<String, Object> params = new HashMap<>();
        params.put("appid",getAppId());
        params.put("secret",getAppSecret());
        params.put("grant_type",getGrantType());
        String body = HttpRequest.get("https://developer.toutiao.com/api/apps/token")
                .form(params)
                .execute()
                .body();
        return getTokenFromResult(body);
    }

    private static String getTokenFromResult(String body) {
        try{
            JSONObject jsonObject = JSONObject.parseObject(body);
            String accessToken = jsonObject.getString("access_token");
            Integer expiresIn = jsonObject.getInteger("expires_in");
            long currentSecond = System.currentTimeMillis() /1000;
            long expires = currentSecond + expiresIn;
            ByteDanceProperties.setToutiaoToken(new ToutiaoToken(accessToken, expires));
            return accessToken;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
    }

    public void setToken(String token) {
        ByteDanceProperties.token = token;
    }

    public static ToutiaoToken getToutiaoToken() {
        return toutiaoToken;
    }

    public static void setToutiaoToken(ToutiaoToken toutiaoToken) {
        ByteDanceProperties.toutiaoToken = toutiaoToken;
    }

    /**
     * 检测图片
     * @param base64
     * @return
     */
    public static HashMap<String, Boolean> getCheckImage(String base64){
        JSONObject all = new JSONObject();
        JSONArray targets = new JSONArray();
        targets.add("ad");
        targets.add("porn");
        targets.add("politics");
        targets.add("disgusting");
        JSONArray tasks = new JSONArray();
        JSONObject tasksItem = new JSONObject();
        tasksItem.put("image_data",base64);
        tasks.add(tasksItem);
        all.put("targets",targets);
        all.put("tasks",tasks);
        String token = getToken();
        String resultStr = HttpRequest.post("https://developer.toutiao.com/api/v2/tags/image/")
                .header("X-Token", token)
                .body(all.toJSONString())
                .execute()
                .body();
        JSONObject parseObject = JSONObject.parseObject(resultStr);
        JSONArray data = parseObject.getJSONArray("data");

        if (data.size()>0){
            JSONArray predicts = data.getJSONObject(0).getJSONArray("predicts");
            return checkPredicts(predicts);
        }
        return null;
    }

    public static boolean getCheckText(String text) {
        JSONObject all = new JSONObject();
        JSONArray tasks = new JSONArray();
        JSONObject tasksItem = new JSONObject();
        tasksItem.put("content",text);
        tasks.add(tasksItem);
        all.put("tasks",tasks);
        String token = getToken();
        String resultStr = HttpRequest.post("https://developer.toutiao.com/api/v2/tags/text/antidirt")
                .header("X-Token", token)
                .body(all.toJSONString())
                .execute()
                .body();
        JSONObject parseObject = JSONObject.parseObject(resultStr);
        JSONArray data = parseObject.getJSONArray("data");

        if (Objects.nonNull(data)){
            if (data.size()>0){
                JSONArray predicts = data.getJSONObject(0).getJSONArray("predicts");
                return checkTextPredicts(predicts);
            }
        }
        return false;
    }

    private static boolean checkTextPredicts(JSONArray predicts) {
        boolean result = true;
        for (int i = 0; i < predicts.size(); i++) {
            JSONObject predict = predicts.getJSONObject(i);
            Integer prob = predict.getInteger("prob");
            if (prob == 1){
                return false;
            }
        }
        return result;
    }

    private static HashMap<String, Boolean> checkPredicts(JSONArray predicts) {
        HashMap<String, Boolean> map = new HashMap<>();
        for (int i = 0; i < predicts.size(); i++) {
            JSONObject predict = predicts.getJSONObject(i);
            Boolean hit = predict.getBoolean("hit");
            String target = predict.getString("target");
            if (hit){
                map.put(target,hit);
            }
        }
        return map;
    }
}
